import '../../public.dart';
import '../common/common_step_indicator.dart';
import '../common/common_pin_input.dart';
import '../common/common_button.dart';

class ChangePinPage extends StatefulWidget {
  const ChangePinPage({super.key});

  @override
  State<ChangePinPage> createState() => _ChangePinPageState();
}

class _ChangePinPageState extends State<ChangePinPage> {
  final List<TextEditingController> _currentPinControllers = List.generate(
    4,
    (_) => TextEditingController(),
  );
  final List<TextEditingController> _newPinControllers = List.generate(
    4,
    (_) => TextEditingController(),
  );
  final List<TextEditingController> _confirmPinControllers = List.generate(
    4,
    (_) => TextEditingController(),
  );
  final List<FocusNode> _currentPinFocusNodes = List.generate(
    4,
    (_) => FocusNode(),
  );
  final List<FocusNode> _newPinFocusNodes = List.generate(
    4,
    (_) => FocusNode(),
  );
  final List<FocusNode> _confirmPinFocusNodes = List.generate(
    4,
    (_) => FocusNode(),
  );

  int _currentStep = 1; // 1: 验证当前PIN, 2: 输入新PIN, 3: 确认新PIN
  String _currentPin = '';
  String _newPin = '';
  String _confirmPin = '';
  bool _isLoading = false;

  @override
  void dispose() {
    for (var controller in _currentPinControllers) {
      controller.dispose();
    }
    for (var controller in _newPinControllers) {
      controller.dispose();
    }
    for (var controller in _confirmPinControllers) {
      controller.dispose();
    }
    for (var focusNode in _currentPinFocusNodes) {
      focusNode.dispose();
    }
    for (var focusNode in _newPinFocusNodes) {
      focusNode.dispose();
    }
    for (var focusNode in _confirmPinFocusNodes) {
      focusNode.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.black87),
          onPressed: _handleBackButton,
        ),
        title: const Text(
          'Change PIN',
          style: TextStyle(
            color: Colors.black87,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: true,
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 步骤指示器
              CommonStepIndicator(
                currentStep: _currentStep,
                stepTitles: ['Current PIN', 'New PIN', 'Confirm'],
              ),
              const SizedBox(height: 40),

              // 标题和说明
              _buildTitleAndDescription(),
              const SizedBox(height: 60),

              // PIN输入区域
              Expanded(
                child: _currentStep == 1
                    ? _buildCurrentPinInput()
                    : _currentStep == 2
                    ? _buildNewPinInput()
                    : _buildConfirmPinInput(),
              ),

              // 底部按钮
              CommonButton(
                text: _currentStep == 1
                    ? 'Verify Current PIN'
                    : _currentStep == 2
                    ? 'Next'
                    : 'Change PIN',
                onPressed: _isLoading
                    ? null
                    : () {
                        if (_currentStep == 1) {
                          _verifyCurrentPin(context.read<UserModel>());
                        } else if (_currentStep == 2) {
                          _nextStep();
                        } else {
                          _confirmPinCode(context.read<UserModel>());
                        }
                      },
                isLoading: _isLoading,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTitleAndDescription() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          _currentStep == 1
              ? 'Verify Current PIN'
              : _currentStep == 2
              ? 'Set New PIN'
              : 'Confirm New PIN',
          style: const TextStyle(
            fontSize: 28,
            fontWeight: FontWeight.w700,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 12),
        Text(
          _currentStep == 1
              ? 'Please enter your current PIN to verify your identity'
              : _currentStep == 2
              ? 'Create a new 4-digit PIN for secure transactions'
              : 'Please re-enter your new PIN to confirm',
          style: TextStyle(
            fontSize: 16,
            color: Colors.grey[600],
            fontWeight: FontWeight.w400,
          ),
        ),
      ],
    );
  }

  Widget _buildCurrentPinInput() {
    return Column(
      children: [
        CommonPinInput(
          controllers: _currentPinControllers,
          focusNodes: _currentPinFocusNodes,
          onPinChanged: (pin) {
            setState(() {
              _currentPin = pin;
            });
          },
        ),
      ],
    );
  }

  Widget _buildNewPinInput() {
    return Column(
      children: [
        CommonPinInput(
          controllers: _newPinControllers,
          focusNodes: _newPinFocusNodes,
          onPinChanged: (pin) {
            setState(() {
              _newPin = pin;
            });
          },
          onPinCompleted: (pin) {
            setState(() {
              _newPin = pin;
            });
            _nextStep();
          },
        ),
        if (_newPin.isNotEmpty)
          Padding(
            padding: const EdgeInsets.only(top: 20),
            child: Text(
              'PIN: ${'*' * _newPin.length}',
              style: TextStyle(fontSize: 14, color: Colors.grey[600]),
            ),
          ),
      ],
    );
  }

  Widget _buildConfirmPinInput() {
    return Column(
      children: [
        CommonPinInput(
          controllers: _confirmPinControllers,
          focusNodes: _confirmPinFocusNodes,
          onPinChanged: (pin) {
            setState(() {
              _confirmPin = pin;
            });
          },
        ),
        if (_confirmPin.isNotEmpty)
          Padding(
            padding: const EdgeInsets.only(top: 20),
            child: Text(
              'PIN: ${'*' * _confirmPin.length}',
              style: TextStyle(fontSize: 14, color: Colors.grey[600]),
            ),
          ),
        if (_newPin != _confirmPin && _confirmPin.length == 4)
          const Padding(
            padding: EdgeInsets.only(top: 20),
            child: Text(
              'PINs do not match',
              style: TextStyle(
                fontSize: 14,
                color: Colors.red,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
      ],
    );
  }

  void _handleBackButton() {
    if (_currentStep == 3) {
      // 第三步：返回上一步（输入新PIN步骤）
      _goBackToSecondStep();
    } else if (_currentStep == 2) {
      // 第二步：返回上一步（验证当前PIN步骤）
      _goBackToFirstStep();
    } else {
      // 第一步：显示确认对话框
      BrnDialogManager.showConfirmDialog(
        context,
        title: 'Exit PIN Change',
        message:
            'Are you sure you want to exit? Your changes will not be saved.',
        cancel: 'Cancel',
        confirm: 'Exit',
        onCancel: () {
          Navigator.of(context).pop(); // 取消弹窗
        },
        onConfirm: () {
          Navigator.of(context).pop(); // 取消弹窗
          Navigator.of(context).pop(); // 退出页面
        },
      );
    }
  }

  void _goBackToFirstStep() {
    // 清除当前PIN码的所有输入
    for (var controller in _currentPinControllers) {
      controller.clear();
    }

    setState(() {
      _currentStep = 1;
      _currentPin = '';
      _newPin = '';
      _confirmPin = '';
    });

    // 重新聚焦到第一个输入框
    _currentPinFocusNodes[0].requestFocus();
  }

  void _goBackToSecondStep() {
    // 清除确认PIN码和新PIN码的所有输入
    for (var controller in _confirmPinControllers) {
      controller.clear();
    }

    for (var controller in _newPinControllers) {
      controller.clear();
    }

    setState(() {
      _currentStep = 2;
      _confirmPin = '';
      _newPin = '';
    });

    // 重新聚焦到第一个新PIN输入框
    _newPinFocusNodes[0].requestFocus();
  }

  void _nextStep() {
    if (_currentStep == 1) {
      // 第一步：验证当前PIN
      if (_currentPin.length == 4) {
        setState(() {
          _currentStep = 2;
        });
        // 延迟聚焦到第一个新PIN输入框
        Future.delayed(const Duration(milliseconds: 100), () {
          _newPinFocusNodes[0].requestFocus();
        });
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Please enter 4 digits'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } else if (_currentStep == 2) {
      // 第二步：到第三步（确认新PIN）
      if (_newPin.length == 4) {
        setState(() {
          _currentStep = 3;
        });
        // 延迟聚焦到第一个确认PIN输入框
        Future.delayed(const Duration(milliseconds: 100), () {
          _confirmPinFocusNodes[0].requestFocus();
        });
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Please enter 4 digits'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  Future<void> _verifyCurrentPin(UserModel model) async {
    if (_currentPin.length != 4) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Please enter 4 digits'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      // 这里验证当前PIN
      await ClientUserApi.checkPin(CheckPinDto(currentPin: _currentPin));

      if (mounted) {
        setState(() {
          _isLoading = false;
        });
        _nextStep();
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Invalid PIN'), backgroundColor: Colors.red),
        );
      }
    }
  }

  Future<void> _confirmPinCode(UserModel model) async {
    if (_confirmPin.length != 4) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Please enter 4 digits'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    if (_newPin != _confirmPin) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('PINs do not match'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      // 这里调用修改PIN的API
      await ClientUserApi.changePin(
        ChangePinDto(verifyCode: model.pinVerifyCode!, newPin: _newPin),
      );

      if (mounted) {
        setState(() {
          _isLoading = false;
        });

        // 显示成功提示
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('PIN changed successfully'),
            backgroundColor: Colors.green,
          ),
        );

        // 返回上一页或跳转到主页
        Navigator.of(context).pop(true);
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Failed to change PIN: ${e.toString()}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }
}
